<?php

namespace app\api\middleware;

use app\common\exception\AdminException;
use app\common\service\user\UserService;
use app\common\util\JwtUtil;
use think\Request;
use think\facade\Db;

class JwtAuth
{
    public function handle(Request $request, \Closure $next)
    {
        $token = $request->header('Authorization'); // 从请求头中获取 Token

        if (!$token) {
            throw new AdminException('Token 缺失', 401);
        }

        // 去掉 "Bearer " 前缀
        if (str_starts_with($token, 'Bearer ')) {
            $token = substr($token, 7);
        }

        $payload = JwtUtil::validateToken($token);
        
        if (!$payload) {
            throw new AdminException('Token 无效或已过期', 401);
        }

        $userService = app()->make(UserService::class);
        // 检查用户状态
        $userInfo = $userService->getInfo($payload['user_id']);
        if (!$userInfo) {
            throw new AdminException('用户不存在', 401);
        }
        if($userInfo['status'] === 0) {
            throw new AdminException('状态异常：禁止访问');
        }

        $ip = $request->ip();
        $ipList = cache('ip_blacklist');
        if ($ipList === null) {
            $ipList = Db::name('ip_blacklist')->where('is_active', 1)->column('ip');
            cache('ip_blacklist', $ipList, 3600); // 缓存1小时
        }

        if(in_array($ip, $ipList)) {
            throw new AdminException('状态异常：禁止访问');
        }

        // 将用户信息存储到请求对象中，方便后续使用
        $request->userInfo = $payload;

        // 刷新 Token 并返回给客户端
        $newToken = JwtUtil::refreshToken($token);
        if ($newToken !== $token) {
            header('Authorization: Bearer ' . $newToken);
        }

        return $next($request);
    }
}